package com.itrip.log.module.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itrip.log.module.db.IDao;
import com.itrip.log.module.db.KVDB;

@Controller
@RequestMapping("/jmonitor")
public class MonitorService extends BaseController {

	@Autowired
	private KVDB kvdb;

	@Autowired
	private IDao daoTemplate;

	private JSONObject buildChart(String render, String type, String xs) {
		JSONObject cpu = new JSONObject();
		cpu.put("x", xs.split(","));
		cpu.put("render", render);
		cpu.put("type", type);
		return cpu;
	}

	@ResponseBody
	@RequestMapping("/getValue")
	public JSONObject getValue(@RequestParam String id) {
		return returnJSON(kvdb.get(id));
	}

	@ResponseBody
	@RequestMapping("/getIds")
	public JSONObject getIds(String name,String project, long start, long end) {
		Map<String, Object> pa = new HashMap<String, Object>();
		pa.put("name", name);
		pa.put("end", end);
		pa.put("start", start);
		pa.put("project", project);
		return returnJSON(daoTemplate.selectList("EmailRecord.getKvId", pa));
	}

	@ResponseBody
	@RequestMapping("/getLogStack")
	public JSONObject getLogStack(@RequestParam String name) {
		List<String> keys = kvdb.getList(name);
		List<String> vals = new ArrayList<String>(keys.size());
		for (String string : keys) {
			vals.add(kvdb.get(string));
		}
		return returnJSON(vals);
	}

	@ResponseBody
	@RequestMapping("/loadChartConfig")
	public JSONArray loadChartConfig() {
		JSONArray datas = new JSONArray();
		datas.add(buildChart("proc", "text", ""));
		datas.add(buildChart("load", "spline", "m1,m5,m15"));
		datas.add(buildChart("cpu", "spline", "id,wa,us,sy"));
		datas.add(buildChart("mem", "area", "MemTotal,MemFree,Cached,SwapFree,SwapTotal"));
		System.out.println(datas);
		return datas;
	}

	@ResponseBody
	@RequestMapping("/loadMap")
	public Object loadMap(String type) {
		HashMap<String, Object> where = new HashMap<String, Object>();
		where.put("type", type);
		List<Object> values = daoTemplate.selectKeyValues("common.queryConfig", where);
		return values;
	}

	@ResponseBody
	@RequestMapping("/loadHosts")
	public Object loadHosts(String type) {
		return daoTemplate.selectKeyValues("common.queryMonitorHosts", null);
	}
}
